# 仅供学习交流 不能用于非法用途
# 通过QQ自动登录进入qq空间

import os
import warnings
import re
import webbrowser
import json

try:
    import requests
except ModuleNotFoundError as import_error:
    os.system(f"pip install {import_error.name}")
    requests = __import__(import_error.name)

warnings.filterwarnings("ignore")
Headers = {'Referer': 'https://xui.ptlogin2.qq.com/', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.3'}

def getCookies():
    url = 'https://xui.ptlogin2.qq.com/cgi-bin/xlogin?appid=715030901&daid=371&ptnoauth=1&s_url=https%3A%2F%2Fqq.com%2F%23'
    resp = requests.get(url, verify = False)
    if resp.status_code != 200:
        return None
        
    cookies = resp.cookies
    pt_local_tk = cookies['pt_local_token']
    return cookies

def getLoginInfos(cookies):
    url = f'https://localhost.ptlogin2.qq.com:4301/pt_get_uins?callback=ptui_getuins_CB&r=0.15048421292301417&pt_local_tk={cookies["pt_local_token"]}'
    resp = requests.get(url, headers=Headers, cookies=cookies, verify = False)
    if resp.status_code != 200:
        return None
        
    sso_list = re.search(r'var var_sso_uin_list=([^;]+);', resp.text)
    if sso_list  == None:
        return None
    
    info_json = sso_list.group(1)
    user_infos  = json.loads(info_json)
    return user_infos 
    
def getUserClientkey(user_info, cookies):
    url = f'https://localhost.ptlogin2.qq.com:4301/pt_get_st?clientuin={user_info["uin"]}&r=0.480288060380329&pt_local_tk={cookies["pt_local_token"]}&callback=__jp0'
    resp = requests.get(url, headers=Headers, cookies=cookies)
    if resp.status_code != 200:
        return None
        
    return resp.cookies['clientkey']

def chooseUserInfo(infos):
    while(True):
        print('当前登录的用户:')
        index = 1
        for info in infos:
            print(f'id:{index}\t{info["uin"]}\t{info["nickname"]+"儿"}')
            index += 1

        choose_id = int(input('输入id选择登录的用户:'))
        choose_id -= 1
        if choose_id < 0 or choose_id >= len(infos):
            print('不正确的输入')
            continue
            
        break;
    return infos[choose_id]
    
def loginInQZone(user_info, cookies, clientkey):
    cookies = cookies.copy()
    cookies['clientkey'] = clientkey
    
    url = f'https://ssl.ptlogin2.qq.com/jump?clientuin={user_info["uin"]}&keyindex=9&pt_aid=549000912&daid=5&u1=https%3A%2F%2Fqzs.qzone.qq.com%2Fqzone%2Fv5%2Floginsucc.html%3Fpara%3Dizone%26specifyurl%3Dhttp%253A%252F%252Fuser.qzone.qq.com%252F{user_info["uin"]}&pt_local_tk={cookies["pt_local_token"]}&pt_3rd_aid=0&ptopt=1&style=40'
    resp = requests.get(url, headers=Headers, cookies=cookies)
    qq_url = re.search(r"ptui_qlogin_CB\('\d+', '([^']+)'", resp.text)
    if qq_url == None:
        return 
    
    return qq_url.group(1)
    
def main():
    cookies = getCookies()
    if cookies == None:
        print('无法获取cookie')
        
    user_infos = getLoginInfos(cookies)
    if user_infos == None or user_infos == []:
        print('当前未登录任何用户')
        return 
    
    choose_user = chooseUserInfo(user_infos)    
    clientkey = getUserClientkey(choose_user, cookies)
    if clientkey == None:
        print('无法获得用户key')
        
    qzone_url = loginInQZone(choose_user, cookies, clientkey)
    if qzone_url == None:
        print('无法获得用户登录地址')
        
    webbrowser.open(qzone_url)

if __name__ == '__main__':
    main()